package saleMarket.controller.basic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import saleMarket.domain.Logistics;
import saleMarket.service.LogisticsService;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author 张瑞祥
 * @version 1.0  12-07-2020
 */

@Slf4j
@WebServlet("/logistics.ctl")
public class LogisticsController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //根据request对象，获得代表参数的JSON字串
        String logistics_json = JSONUtil.getJSON(request);
        //将JSON字串解析为Logistics对象
        Logistics logisticsToAdd = JSON.parseObject(logistics_json, Logistics.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加Logistics对象
        try {
           if(LogisticsService.getInstance().add(logisticsToAdd)) {
               message.put("message", "增加成功");
           }else {
               message.put("message", "增加失败");
           }
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            message.put("message", "网络异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //从JSONObject对象中读取键“id”的值（Java Object对象），
        Object id_obj = request.getParameter("id");
        int id_int = Integer.parseInt(id_obj.toString());
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //到数据库表中删除对应的Logistics
           if(LogisticsService.getInstance().delete(id_int)) {
               respMessage_jsonObj.put("message", "删除成功");
           }else {
               respMessage_jsonObj.put("message", "删除失败");
           }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }

    @Override
    protected void doPut(HttpServletRequest request,HttpServletResponse response)
            throws ServletException,IOException{
        //根据request对象，获得代表参数的JSON字串
        String logistics_json = JSONUtil.getJSON(request);
        //将JSON字串解析为Logistics对象
        Logistics logisticsToUpdate = JSON.parseObject(logistics_json, Logistics.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表修改Logistics对象对应的记录
        try {
            if(LogisticsService.getInstance().update(logisticsToUpdate)) {
                message.put("message", "修改成功");
            }else {
                message.put("message", "修改失败");
            }
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            message.put("message", "网络异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        Object id_obj = request.getParameter("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个Logistics对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseLogistics(id_int, response);
            } else {
                responseLogisticses(response);
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            e.printStackTrace();
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
    }

    //响应一个Logistics对象
    private void responseLogistics(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //根据id查找Logistics
        Collection<Logistics> logisticses = new ArrayList<>();
        Logistics logistics = LogisticsService.getInstance().find(id);
        logisticses.add(logistics);
        //第二个参数可以防止循环引用
        String logisticses_jsonStr = JSON.toJSONString(logisticses,
                SerializerFeature.DisableCircularReferenceDetect);
        //响应Logistics_json到前端
        response.getWriter().println(logisticses_jsonStr);
    }

    //按分页信息响应符合条件的Logistics对象和对象总数
    private void responseLogisticses(HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //分页获得满足条件的所有Logistics
        Collection<Logistics> logisticses = LogisticsService.getInstance()
                .findAll();
        //第二个参数可以防止循环引用
        String logisticses_jsonStr = JSON.toJSONString(logisticses,
                SerializerFeature.DisableCircularReferenceDetect);
        //响应resp_jsonObj到前端
        response.getWriter().println(logisticses_jsonStr);
    }

}
